﻿using System;
using System.Collections.Generic;
using System.Linq;

public class OrderService
{
    private List<Order> orders = new List<Order>();

    public void AddOrder(Order order)
    {
        if (orders.Any(o => o.OrderId == order.OrderId))
        {
            throw new InvalidOperationException("添加订单失败：订单编号已存在。");
        }
        orders.Add(order);
    }

    public void RemoveOrder(int orderId)
    {
        var order = orders.FirstOrDefault(o => o.OrderId == orderId);
        if (order == null)
        {
            throw new InvalidOperationException("删除订单失败：未找到订单。");
        }
        orders.Remove(order);
    }

    public void ModifyOrder(Order order)
    {
        var index = orders.FindIndex(o => o.OrderId == order.OrderId);
        if (index == -1)
        {
            throw new InvalidOperationException("修改订单失败：未找到订单。");
        }
        orders[index] = order;
    }

    public IEnumerable<Order> QueryOrders(Func<Order, bool> predicate)
    {
        return orders.Where(predicate).OrderBy(o => o.TotalAmount);
    }

    public void PrintAllOrders()
    {
        if (orders.Count == 0)
        {
            Console.WriteLine("订单列表为空。");
            return;
        }
        foreach (var order in orders)
        {
            Console.WriteLine(order);
        }
    }

    public void SortOrders(Func<Order, object> keySelector = null)
    {
        orders = (keySelector == null ? orders.OrderBy(o => o.OrderId) : orders.OrderBy(keySelector)).ToList();
    }
}
